
const { Client } = require('node-osc');
const WebSocket = require('ws');
const open = require('open');

const server = new WebSocket.Server({ port: 3228 });

console.log("Waiting for connection from browser...");
open('http://127.0.0.1:8088/');

server.on('connection', ws => {
  console.log("Connected. Waiting for data...");
  ws.on('message', function message(data) {
    if (data == 0) {
      console.log("Got heart rate: 0 bpm, skipping parameter update...");
    } else {
      console.log('Got heart rate: %s bpm', data);
      const client = new Client('localhost', 9000);
      const Heartrate = {
        address: "/avatar/parameters/Heartrate",
        args:
        {
          type: "f",
          value: data / 127 - 1
        }
      };
      const HeartRateFloat = {
        address: "/avatar/parameters/HeartRateFloat",
        args:
        {
          type: "f",
          value: data / 127 - 1
        }
      };
      const Heartrate2 = {
        address: "/avatar/parameters/Heartrate2",
        args:
        {
          type: "f",
          value: data / 255
        }
      };
      const HeartRateFloat01 = {
        address: "/avatar/parameters/HeartRateFloat01",
        args:
        {
          type: "f",
          value: data / 255
        }
      };
      const Heartrate3 = {
        address: "/avatar/parameters/Heartrate3",
        args:
        {
          type: "i",
          value: data
        }
      };
      const HeartRateInt = {
        address: "/avatar/parameters/HeartRateInt",
        args:
        {
          type: "i",
          value: data
        }
      };
      client.send(Heartrate);
      client.send(Heartrate2);
      client.send(Heartrate3);
      client.send(HeartRateFloat);
      client.send(HeartRateFloat01);
      client.send(HeartRateInt);
    }
  });
});